package com.nulstudio.cloud.commodity.controller;

import com.github.pagehelper.PageInfo;
import com.nulstudio.cloud.commodity.domain.dto.CommodityDto;
import com.nulstudio.cloud.common.domain.vo.CommodityVo;
import com.nulstudio.cloud.commodity.service.CommodityService;
import com.nulstudio.cloud.common.util.NulResult;
import jakarta.annotation.Resource;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Resource
    @NonNull
    private CommodityService commodityService;

    @GetMapping
    @NonNull
    public NulResult<NulResult.PageInfoResult<CommodityVo>> all(
            @RequestParam(name = "name", defaultValue = "") @NonNull String name,
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "pageSize", defaultValue = "100000") int pageSize
    ) {
        final PageInfo<CommodityVo> pageInfo = commodityService.fetchAll(name, page, pageSize);
        return NulResult.response(pageInfo.getList(), pageInfo.getTotal());
    }

    @GetMapping("/{id}")
    public NulResult<CommodityVo> get(@PathVariable("id") int id) {
        return NulResult.response(commodityService.getCommodityById(id));
    }

    @PostMapping
    @NonNull
    public NulResult<Void> create(@RequestBody @NonNull CommodityDto commodityDto) {
        commodityService.create(commodityDto);
        return NulResult.response();
    }

    @PutMapping("/{id}")
    @NonNull
    public NulResult<Void> update(@PathVariable int id, @RequestBody @NonNull CommodityDto commodityDto) {
        commodityService.update(id, commodityDto);
        return NulResult.response();
    }

    @DeleteMapping
    @NonNull
    public NulResult<Void> delete(@RequestParam List<Integer> id) {
        commodityService.delete(id);
        return NulResult.response();
    }

    @DeleteMapping("/{id}")
    @NonNull
    public NulResult<Void> delete(@PathVariable int id) {
        commodityService.delete(id);
        return NulResult.response();
    }
}
